package server;

import java.util.Iterator;
import java.util.LinkedList;

import Exceptions.NoRecordException;
import util.Record;

public class RecordHandler {
	private LinkedList<Record> list;
	private static int currentRecNbr;
	public RecordHandler() {
		list = new LinkedList<Record>();
	}
	
	public boolean addRecord(Record rec){
		return list.add(rec);
	}
	
	/**
	 * Returns the a list of records, null if it doesn't exist.  
	 * @throws NoRecordException 
	 * 
	 */
	public LinkedList<Record> getRecordListByPnbr(String pnbr) throws NoRecordException{
		LinkedList<Record> patientRecordlist = new LinkedList<Record>();
		for(Record rec:list){
			if(rec.getPatientPnbr().equals(pnbr)){
				patientRecordlist.add(rec);
			}
		}
		if(patientRecordlist.isEmpty()){
			throw new NoRecordException("No record exist of pNbr: " + pnbr);
		}
		return patientRecordlist;
	}
	 
	/**
	 * Deletes the document with a specified number
	 * @param num the specified number
	 * @return true if the document were removed
	 */
	public boolean deleteRecordByRecordNbr(String num){
		Record rec;
		Iterator<Record> itr = list.iterator();
		while(itr.hasNext()){
			rec = itr.next();
			if(rec.getRecordNbr().equals(num)){
				itr.remove();
				return true;
			}
		}
		return false;
	}	
		
	/**
	 * 
	 * @param num
	 * @return
	 * @throws NoRecordException 
	 */
	public Record getRecordByRecordNbr(String num) throws NoRecordException{
		for(Record rec:list){
			if(rec.getRecordNbr().equals(num)){
				return rec;
			}
		}
		throw new NoRecordException("No record of: " + num);
	}
	/**
	 * 
	 * @param rec
	 * @return
	 */
	public boolean updateRecord(Record rec){
		for(Record currentrec:list){
			if(currentrec.getRecordNbr().equals(rec.getRecordNbr())){
				currentrec = rec;
				return true;
			}
		}
		return false;
	}
	
	public String getNewRecNumber(){
		return Integer.toString(currentRecNbr++);
	}
	
	
}
